var express = require('express');
var _ = require("underscore");
var Page = require('../models/page');
    //codeState = boxSim.codeState;
var Box = require('../models/boxes');
var Buyer = require('../models/buyer');
var Sim = require('../models/sim');
var Log = require('../models/log');
var BoxBuyer = require('../models/box_buyer');
var User = require('../models/user');
var mqtt = require('mqtt');
var async=require('async');
var Billing=require('../models/billing');
var Fault = require('../models/fault');
var Prize = require('../models/prize');
var Active = require('../models/active');
var fs = require('fs');
var gm = require('gm');//处理图片
var xlsx = require('node-xlsx');
var request = require('request');
var mqttclient = mqtt.connect('mqtt://115.28.90.45:1883');
var debug = require('debug')('routes:index');
//client = mqtt.createClient(1883, '114.215.137.61');
mqttclient.subscribe('fault');
//    client.publish('13439221372', 'open1');
//    client.publish('fault', '13012344444 1');
mqttclient.on('message', function (topic, message) {
    console.log(message.split(' ')[0]+"----------"+message.split(' ')[1]);
    if(message.split(' ')[1]==1){
        new Fault({
            sim:message.split(' ')[0],
            date: new Date(),
            ftype: message.split(' ')[1], //操作内容
            content: "连不上互联网"
        }).save();
    }else if(message.split(' ')[1]==2){
        new Fault({
            sim:message.split(' ')[0],
            date: new Date(),
            ftype: message.split(' ')[1], //操作内容
            content: "连不上服务器"
        }).save();
    }else if(message.split(' ')[1]==3){
        new Fault({
            sim:message.split(' ')[0],
            date: new Date(),
            ftype: message.split(' ')[1], //操作内容
            content: "Sim卡欠费"
        }).save();
    }else if(message.split(' ')[1]==4){
        new Fault({
            sim:message.split(' ')[0],
            date: new Date(),
            ftype: message.split(' ')[1], //操作内容
            content: "连接不上Sim卡"
        }).save();
    }
});

require('date-utils');
/* GET home page. */

module.exports = function(app) {
    app.get('/',function(req,res){
        res.render('index',{
            sess:0
        });
    });

    app.post('/',function(req,res){
        var username=req.body.username;
        var password = req.body.pwd;
        if(username=="admin"){
            new User().findUserByName(username,function(err,datas){
                if(err){
                    return res.render('index',{
                        name:username,
                        pwd:req.body.password,
                        error:'服务器繁忙，请稍后再试！'
                    });
                }
                if(datas){
                    if(password!=datas.password){
                        return res.render('index',{
                            username:username,
                            pwd:req.body.password,
                            error:'密码不正确，请重新输入！'
                        });
                    }
                    req.session.user=datas;
                    new Log({
                        box_id: " ",
                        user: req.session.user.user, //操作人
                        date: new Date(), //操作日期
                        operation: "登陆系统" //操作内容
                    }).save();
                    req.flash('success', '登陆成功.');
                    return res.redirect('/box_management');
                }
            })
        }else{
            new Buyer().findAccountByAccount(username,function(err,doc) {
                if (doc) {
                    if (password != doc.password) {
                        return res.render('index', {
                            username: username,
                            pwd: req.body.password,
                            error: '密码不正确，请重新输入！'
                        });
                    }else{
                        req.session.user=doc;
                        //req.flash('success', '登陆成功.');
                        return res.redirect('/user_system?account='+username+'&&state=ok');
                    }
                }else{
                    return res.render('index', {
                        name: username,
                        pwd: req.body.password,
                        error: '用户名不存在，请重新输入'
                    });
                }
            });
        }
    });
    app.get('/user_system',function(req,res){
        var account=req.query.account;
            res.render('user_system',{
                account:account
            });
    });
    //购买人箱子管理页面
    app.get('/user_system/buyer_box',function(req,res){
        var account=req.query.account;
        new Buyer().findAccountByAccount(account,function(err,doc){
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    var page = new Page(req.query.num);
                    var obj = {
                        page: page,
                        search: options
                    };
                        new Box().findForPage(obj, function (err, count, pageCount, datas) {
                            var box = datas;
                            page.pageCount = pageCount;
                            res.render('buyer_box', {
                                datas: box,
                                buyerid:buyer_id,
                                account:account,
                                page:page
                            });
                        });
                }else{
                    req.flash('error', '您没有绑定箱子.');
                    return res.redirect('/user_system/main');
                }
            });
        });
    });
    //购买人箱子详情页面
    app.get('/user_system/userbox_order',function(req,res){
        var boxid=req.query.boxid;
        var buyerid=req.query.buyerid;
        new Box().findBoxById(boxid,function(datas){
            var boxDatas=datas;
            new Sim().findSimById(boxid,function(datas){
                var simDatas=datas;
                new Buyer().findById(buyerid,function(datas){
                    var buyerdatas=datas;
                    res.render('userbox_order',{
                        simdatas:simDatas,
                        boxdatas:boxDatas[0],
                        buyerdatas:buyerdatas
                    });
                });
            });
        });
    });
    //用户门状态页面
    app.get('/user_system/user_doors',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        if(index==0) {
            new Box().findByBoxId(boxid, function (box) {
                var list = box.data;
                res.render("user_door", {
                    "boxid": boxid,
                    "doordatas": list
                });
            });
        }else if(index=="all"){
            var doorsnum=req.query.doorsnum;
            var doors = [];
            for (var i = 0; i < doorsnum; i++) {
                doors.push({
                    index: i + 1,
                    empty: true,
                    password: "",
                    opentime: "",
                    owner: ""
                });
            }
            new Sim().findSimById(boxid,function(datas){
                var sim=datas.sim;
                var j=1;
                for(var i=0;i<doorsnum;i++){
                    mqttclient.publish(sim, 'open'+j);
                }
            });
            new Box().updateDoorById(boxid,doors,function(){
                new Box().findByBoxId(boxid, function(box) {
                    var list = box.data;
                    res.render("user_door", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
            });
        }else{
            new Box().updateByBoxidAndIndex(boxid, index,true,function(data){
                new Box().findByBoxId(boxid, function(box) {
                    var list = box.data;
                    res.render("user_door", {
                        "boxid": boxid,
                        "doordatas": list
                    });
                });
                new Sim().findSimById(boxid,function(datas) {
                    var sim = datas.sim;
                    mqttclient.publish(sim, 'open'+index);
                });
            });
        }
    });

    //设置计费页面
    app.get('/user_system/billing',function(req,res){
        var boxid=req.query.boxid;
        var account=req.query.account;
        new Billing().findSpriceById(boxid,function(datas){
            if(datas==""){
                res.render('billing',{
                    boxid:boxid,
                    account:account,
                    pri:0
                });
            }else{
                var standard=datas[0].standard;
                var price=datas[0].price;
                var less=datas[0].less;
                var lessprice=datas[0].lessprice;
                var more=datas[0].more;
                var moreprice=datas[0].moreprice;
                res.render('billing',{
                    boxid:boxid,
                    account:account,
                    pri:1,
                    standard:standard,
                    price:price,
                    less:less,
                    lessprice:lessprice,
                    more:more,
                    moreprice:moreprice
                });
            }
        });
    });
    //提交计费设置
    app.post('/user_system/billing',function(req,res){
        var boxid=req.body.boxid;
        var account=req.body.account;
        var standard = req.body.standard;
        var timetype = req.body.timetype;
        var price = req.body.price;
        var less = req.body.less;
        var lesstimetype = req.body.lesstimetype;
        var lessprice = req.body.lessprice;
        var more = req.body.more;
        var moretimetype = req.body.moretimetype;
        var moreprice = req.body.moreprice;
        if(less==""&&more==""){
            if(timetype==1){
            new Billing().removepriceById(boxid,function(err){
                var stan=standard*60;
                new Billing({
                    box_id: boxid,
                    standard:stan,
                    price: price,
                    less: less,
                    lessprice:lessprice,
                    more:more,
                    moreprice:moreprice
                }).save();
            });

            }else if(timetype==0){
                new Billing().removepriceById(boxid,function(err){
                    new Billing({
                        box_id: boxid,
                        standard:standard,
                        price: price,
                        less: less,
                        lessprice:lessprice,
                        more:more,
                        moreprice:moreprice
                    }).save();
                });
            }
        }else if(less==""&&more!==""){
            if(timetype==1){
                var stans=standard*60;
                if(moretimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var mor=more*60;
                        new Billing({
                            box_id: boxid,
                            standard:stans,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:stans,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }else if(timetype==0){
                if(moretimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var mor=more*60;
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }
        }else if(less!==""&&more==""){
            if(timetype==1){
                var sta=standard*60;
                if(lesstimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var les=less*60;
                        new Billing({
                            box_id: boxid,
                            standard:sta,
                            price: price,
                            less: les,
                            lessprice:lessprice,
                            more:mor,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(lesstimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:sta,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }else if(timetype==0){
                if(lesstimetype==1){
                    new Billing().removepriceById(boxid,function(err){
                        var le=less*60;
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: le,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });

                }else if(moretimetype==0){
                    new Billing().removepriceById(boxid,function(err){
                        new Billing({
                            box_id: boxid,
                            standard:standard,
                            price: price,
                            less: less,
                            lessprice:lessprice,
                            more:more,
                            moreprice:moreprice
                        }).save();
                    });
                }
            }
        }else if(less!==""&&more!==""){
            if(timetype==1){
                var st=standard*60;
                if(lesstimetype==1){
                    var lesss=less*60;
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moree=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: lesss,
                                lessprice:lessprice,
                                more:moree,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: lesss,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }else if(lesstimetype==0){
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:moreee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:st,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }
            }else if(timetype==0){
                if(lesstimetype==1){
                    var lessss=less*60;
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreeeee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: lessss,
                                lessprice:lessprice,
                                more:moreeeee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: lessss,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }else if(lesstimetype==0){
                    if(moretimetype==1){
                        new Billing().removepriceById(boxid,function(err){
                            var moreeeeee=more*60;
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:moreeeeee,
                                moreprice:moreprice
                            }).save();
                        });

                    }else if(moretimetype==0){
                        new Billing().removepriceById(boxid,function(err){
                            new Billing({
                                box_id: boxid,
                                standard:standard,
                                price: price,
                                less: less,
                                lessprice:lessprice,
                                more:more,
                                moreprice:moreprice
                            }).save();
                        });
                    }
                }
            }
        }
        req.flash('success', '费用设置成功.');
        return res.redirect('/user_system/buyer_box?num=1&&boxid='+boxid+'&&account='+account);
    });

    app.get('/box_management/update_pwd',function(req,res){
        res.render('update_pwd',{
        });
    });

    app.post('/box_management/update_pwd',function(req,res){
        var opwd=req.body.opwd;
        var password=req.body.npwd1;
        var admin="admin";
        new User().findUserByName(admin,function(err,datas){
            if(err){
                return res.render('update_pwd',{
                    error:'服务器繁忙，请稍后再试！'
                });
            }
            if(datas) {
                if (opwd != datas.password) {
                    return res.render('update_pwd', {
                        error: '旧密码不正确，请重新输入！'
                    });
                }
                new User().updatePwd(admin,password,function(err){
                    new User().findUserByName(admin,function(err,datas){
                        req.session.user=datas;
                        new Log({
                            box_id: " ",
                            user: "管理员", //操作人
                            date: new Date(), //操作日期
                            operation: "修改管理员密码" //操作内容
                        }).save();
                        req.flash('success', '密码修改成功.');
                        return res.redirect('/box_management/update_pwd');
                    });

                });
            }
        });
    });
    app.get('/box_management',function(req,res){
        res.render('box_management');
    });
    app.get('/box_management/main',function(req,res){
        res.render('main');
    });
    app.get('/user_system/main',function(req,res){
        res.render('main');
    });

    app.get('/logout',function(req,res){
        new Log({
            box_id: " ",
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "退出系统" //操作内容
        }).save();
        req.session.user=null;
        res.redirect('/');
    });

    app.get('/user_logout',function(req,res){
        req.session.user=null;
        res.redirect('/');
    });

    app.get('/box_management/log', function(req, res) {
        var sess=req.session.user;
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Log().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            var dates=[];
            for(var i=0;i<datas.length;i++){
                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
            }
            res.render('log', {
                datas: datas,
                dates:dates,
                page: page
            });
        })
    });
    app.get('/box_management/main', function(req, res) {
        res.render('main', {});
    });
    //Sim卡页面
    app.get('/box_management/code', function(req, res) {
        var sim = req.query.sim;
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Sim().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            res.render('qrcodeM', {
                datas: datas,
                page: page
            });
        })
        if (sim == "ok") {
            console.log("进入二维码管理");

        } else {
            //修改Sim卡打印次数
            new Sim().updateStateBySim(sim, function(err) {
            });
            //操作记录
            new Log({
                box_id: " ",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "打印二维码,号码为:"+sim+"" //操作内容
            }).save();

        }
    });
    //生成Sim卡页面
    app.get('/box_management/create_device',function(req,res){

        res.render('create_device');
    });

    app.get('/box_management/update_sim_wifi',function(req,res){
        console.log(req.query.phone);
        res.render('update_sim_wifi',{id:req.query.id,phone:req.query.phone});
    });

    app.post('/box_management/update_sim_wifi',function(req,res){
        var options = {wifissid:req.body.wifissid,wifipass:req.body.wifipass};
        new Sim().updateSimColumn(req.body.id,options,function(err){
            //res.render('update_sim_wifi');
            if(err){
                res.render('update_sim_wifi',{id:req.body.id});
            }else{
                var ssid = 'wifissid:'+req.body.wifissid;
                var pass = 'wifissid:'+req.body.wifipass
                console.log(req.body.phone+'   '+ssid+'   '+pass);
                console.log('xxxxxxxxxxxxxxxxxxxxxxx');
                mqttclient.publish(req.body.phone, ssid);
                mqttclient.publish(req.body.phone, pass);
                res.redirect('/box_management/code?num=1&&sim=ok');
            }

        });
    });
/*
//生成Sim卡页面
    app.get('/box_management/create_sim',function(req,res){
        res.render('create_sim');
    });
*/

    app.post('/box_management/create_device',function(req,res){
        var data = xlsx.parse(req.files.device_data.path)[0].data;
        var count = 1;
        async.whilst(function(){
            return count<data.length;
        },function(callback) {
            new Sim().findSimBySim(data[count][0],function(err,doc){//检查是否存在，存在则跳过
                if(doc){
                    debug('cunzai.............................');
                    count++;
                    callback();
                }else{
                    request.post({url:'http://127.0.0.1/hdc/applyBeacons', form: {device:data[count].join(',')}}, function(err,httpResponse,body){
                        count++;
                        debug('~~~~~~~~~~~~~~~~~~~');
                        debug(body);
                        debug('~~~~~~~~~~~~~~~~~~~');
                        callback();
                    });
                }

            });

        },function(err){
            return res.redirect('/box_management/code?num=1&&sim=ok');
        });


    });

    //提交Sim卡生成
    app.post('/box_management/create_sim',function(req,res){
        var sim=req.body.sim;
        var operators=req.body.operators;
        var charge=req.body.charge;
        new Sim().findSimBySim(sim, function(err, doc) {
            if (doc) err = 'Sim卡已被使用,请重新输入.';
            if (err) {
                req.flash('error', err);
                return res.redirect('/box_management/create_sim');
            }
            var nSim = new Sim({
                box_id:"未绑定",
                sim: sim,
                state: 0,
                operators: operators, //sim卡所属运营商
                charge: charge //资费
            });
            nSim.save(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Log({
                box_id: "",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "生成Sim卡(卡号为:"+sim+")" //操作内容
            }).save();
            req.flash('success', 'Sim卡已经生成.');
            return res.redirect('/box_management/code?num=1&&sim=ok');
        });
    });

    //箱子自定义生成
    app.post('/box_management/create',function(req,res){
        var sim=req.body.sim;//获取sim卡号
        var buyer=req.body.buyer;//获取购买人姓名
        var box_layout=req.body.boxlayout;//获取箱子布局
        var doorsnum=req.body.doorNum;//获取格子数
        var codelayout=req.body.code_layout;//获取贴码位置
        var tim=new Date().getTime();
        var boxid="SB_"+tim;
        var doors = [];
        for (var i = 0; i < doorsnum; i++) {
            doors.push({
                index: i + 1,
                empty: true,
                password: "",
                opentime: "",
                owner: "",
                prize_id:null,
                discount_price:null
            });
        }
        if(buyer==0){
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors,
                limit:true
            });
            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }else {
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors,
                limit:true
            });

            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Buyer().findBuyerById(buyer,function(datas){
                var buyer_id=datas.buyer_id;
                var nBoxBuyer = new BoxBuyer({
                    buyer_id:buyer_id,
                    box_id: boxid
                });
                nBoxBuyer.save(function (err) {});
            });
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "自定义生成箱子(格子数为:"+doorsnum+")" //操作内容
        }).save();
        req.flash('success', '箱子已经生成.');
        return res.redirect('/box_management/box?num=1');
    });

    //箱子管理界面
    app.get('/box_management/box',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Box().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
                console.log("boxM-----" + err);
            }

            var count = 0;
            async.whilst(function(){
                return count<datas.length;
            },function(callback) {
                new Sim().findSimById(datas[count].box_id,function(sim){
                    datas[count].sim = sim.sim;
                    count++;
                    callback();

                });
            },function(err){
                //var boxdatas=datas;
                page.pageCount = pageCount;
                res.render('boxM', {
                    datas: datas,
                    page: page
                });
            });


            /*datas.forEach(function(box,index){//遍历添加对应的sim卡号，应该使用population最好
                new Sim().findSimById(box.box_id,function(sim){
                    datas[index].sim = sim.sim;
                    if(index==(datas.length-1)){
                        var boxdatas=datas;
                        page.pageCount = pageCount;
                        res.render('boxM', {
                            datas: boxdatas,
                            page: page
                        });
                    }
                });
            });*/
        });
    });

    //商品管理
    app.get('/box_management/prize',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Prize().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            var boxdatas=datas;
            page.pageCount = pageCount;
            res.render('prizeM', {
                datas: boxdatas,
                page: page
            });
        })
    });
    //新建商品
    app.get('/box_management/create_prize',function(req,res){
        res.render('create_prize');
    });

    //创建商品提交
    app.post('/box_management/create_prize',function(req,res){
        var name=req.body.name;
        var price=req.body.price;
        var imgurl=req.body.imgurl;
        var taobao_url=req.body.taobao_url;
        var wechat_productId = req.body.wechat_productId;
        new Prize({
            name: name, //商品名称
            price:price, //商品价格
            imgurl:imgurl, //商品图片
            taobao_url:taobao_url, //商品淘宝链接
            wechat_productId:wechat_productId //微信购买链接
        }).save();
        res.redirect('/box_management/prize?num=1');
    });

    //商品详情
    app.get('/box_management/prize_order',function(req,res){
        var prizeid=req.query.prize;
        new Prize().findPrizeById(prizeid,function(datas){
            res.render('prize_order',{data:datas[0]});
        });
    });

    //编辑奖品
    app.get('/box_management/edit_prize',function(req,res){
        var prize_id=req.query.prize;
        new Prize().findPrizeById(prize_id,function(datas) {
            res.render('edit_prize',{prizedata:datas[0],id:prize_id});
        });

    });

    //编辑奖品提交
    app.post('/box_management/edit_prize',function(req,res){
        var prize_id=req.body.id;
        var name=req.body.name;
        var price=req.body.price;
        var imgurl=req.body.imgurl;
        var taobao_url=req.body.taobao_url;
        var wechat_productId = req.body.wechat_productId;
        new Prize().updatePrizeById(prize_id,name,price,imgurl,taobao_url,wechat_productId,function(err) {
            console.log(err);
        });
        res.redirect('/box_management/prize?num=1');
    });

    //绑定商品页
    app.get('/box_management/binding_list',function(req,res){
        var boxid=req.query.boxid;
        var arr=[];
        new Box().findBoxById(boxid,function(data){
            var count = 0;
            var datas=data[0].doors;
            async.whilst(function(){
                return count<datas.length;
            },function(callback) {
                var door={};
                if(datas[count].prize_id){
                    new Prize().findPrizeById(datas[count].prize_id,function(result){
                        door.index=datas[count].index;
                        door.price=result[0].price;
                        door.imgurl=result[0].imgurl;
                        door.name=result[0].name;
                        door.prize_id=datas[count].prize_id;
                        door.taobao_url=result[0].taobao_url;
                        door.discount_price=datas[count].discount_price;
                        arr.push(door);
                        count++;
                        callback();
                    });
                }else{
                    door.index=datas[count].index;
                    door.discount_price=datas[count].discount_price;
                    door.prize_id=null;
                    arr.push(door);
                    count++;
                    callback();
                }
            },function(err){
                res.render('box_prize',{datas:arr,boxid:boxid,box_layout:data[0].box_layout});
            });
        });
    });

    //绑定商品
    app.get('/box_management/Binding',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        new Prize().findAllPrize(function(err,datas){
            res.render('Binding',{datas:datas,boxid:boxid,index:index});
        });
    });
    //编辑绑定商品
    app.get('/box_management/edit_Binding',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        new Box().findByBoxId(boxid,function(box){
            var door=box.data[index-1];
            console.log(door);
            new Prize().findAllPrize(function(err,datas){
                var name='';
                for(var i=0;i<datas.length;i++){
                    if(door.prize_id==datas[i]._id){
                        name=datas[i].name;
                    }
                }
                res.render('edit_Binding',{datas:datas,boxid:boxid,index:index,prize_id:door.prize_id,discount_price:door.discount_price,name:name});
            });
        });
    });
    //绑定商品提交
    app.post('/box_management/Binding',function(req,res){
        var boxid=req.body.boxid;
        var index=req.body.index;
        var prize=req.body.prize;
        var discount_price=req.body.discount_price;
        new Box().updateBinding(boxid,index,prize,discount_price,function(boxid){
            res.redirect('/box_management/binding_list?boxid='+boxid);
        });
    });

    //解绑商品
    app.get('/box_management/reBinding',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        new Box().updateReBinding(boxid,index,function(boxid){
            res.redirect('/box_management/binding_list?boxid='+boxid);
        });
    });

    //删除商品卡
    app.get('/box_management/remove_prize',function(req,res){
        var prize=req.query.prize;
        new Box().findAllBox(function(err,datas){
            var count = 0;
            async.whilst(function(){
                return count<datas.length;
            },function(callback) {
                var doors=datas[count].doors;
                var count1=0;
                async.whilst(function(){
                    return count1<doors.length;
                },function(callback1) {
                    if(doors[count1].prize_id){
                        console.log(count1);
                        if(doors[count1].prize_id==prize){
                            req.flash('error', '此商品已绑定箱子，不可删除.');
                            return res.redirect('/box_management/prize?num=1');
                        }
                    }
                    count1++;
                    callback1();

                },function(err){
                    count++;
                    callback();
                });

            },function(err){
                new Prize().removeIdById(prize,function(err){
                    if(err){
                        req.flash('error', '删除失败,请重试.');
                        return res.redirect('/box_management/prize?num=1');
                    }else{
                        req.flash('success', '删除成功.');
                        return res.redirect('/box_management/prize?num=1');
                    }
                });
            });
            //req.flash('error', '...........');
            //return res.redirect('/box_management/prize?num=1');
        });
    });

    //删除箱子
    app.get('/box_management/rembox',function(req,res){
        var boxid=req.query.boxid;
        new Box().removeById(boxid,function(err){
            new BoxBuyer().removeBuyerById(boxid,function(err){
                new Sim().updateIdById(boxid,function(err){
                    req.flash('success', '箱子已经删除.');
                    return res.redirect('/box_management/box?num=1');
                });
            });
        });
    });

    //上传图片
    app.post('/box_management/uploadimg',function(req,res){
        var data = JSON.parse(req.body.avatar_data);
        if(!data){
            res.send(false);
        }
        var filename = req.files.avatar_file.name;
        var x = Math.round(data.x);
        var y = Math.round(data.y);
        var height = Math.round(data.height);
        var width = Math.round(data.width);
        var oldpath = data.oldpath;

        var path1 = './uploads/';
        var path2 = './public/images/prize/';
        if(!fs.existsSync(path2)){
            fs.mkdirSync(path2);
        }
        //res.send({
        //    state:200,
        //    message:'上传成功',
        //    result:'./public/uploads/'+filename
        //});
        gm(req.files.avatar_file.path).crop(width, height, x, y)
            .resize(320, 320)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
            .noProfile()
            .write(path2+filename, function (err) {
                if (!err){
                    fs.unlinkSync(req.files.avatar_file.path);//删除upload目录下的文件
                    //console.log('删除图片111');
                    if(fs.existsSync('./public'+oldpath)){
                        fs.unlinkSync('./public'+oldpath);//删除用户目录下的文件
                    }
                    res.send({
                        state:200,
                        message:'上传成功',
                        result:'/images/prize/'+filename
                    });
                }
            });
    });

    //自定义生成箱子页面
    app.get('/box_management/create',function(req,res){
        new Buyer().findAll(function(datas){
            var buyerdatas=datas;
            new Sim().findAllSim(function(datas){
                var simdatas=datas;
                res.render('create',{
                    buyerdatas:buyerdatas,
                    simdatas:simdatas
                });
            });
        });
    });
    //编辑箱子页面
    app.get('/box_management/edit',function(req,res){
        var boxid=req.query.boxid;
        new BoxBuyer().findBuyerById(boxid,function(datas){
            if(datas==null){
                new Buyer().findAll(function(datas){
                    var buyerdatas=datas;
                    new Sim().findAllSim(function(datas){
                        var simdatas=datas;
                        var buyer="请选择用户名";
                        new Sim().findSimById(boxid,function(datas){
                            var sim=datas.sim;
                            new Box().findBoxById(boxid,function(datas){
                                var boxdatas=datas;
                                res.render('edit',{
                                    buyerdatas:buyerdatas,
                                    simdatas:simdatas,
                                    boxid:boxid,
                                    buyer:buyer,
                                    sim:sim,
                                    boxdatas:boxdatas
                                });
                            });
                        });
                    });
                });
            }else{
                var buyerid=datas.buyer_id;
                new Buyer().findAll(function(datas){
                    var buyerdatas=datas;
                    new Sim().findAllSim(function(datas){
                        var simdatas=datas;
                        new Buyer().findById(buyerid,function(datas){
                            var buyer=datas.buyer;
                            new Sim().findSimById(boxid,function(datas){
                                var sim=datas.sim;
                                new Box().findBoxById(boxid,function(datas){
                                    var boxdatas=datas;
                                    res.render('edit',{
                                        buyerdatas:buyerdatas,
                                        simdatas:simdatas,
                                        boxid:boxid,
                                        buyer:buyer,
                                        sim:sim,
                                        boxdatas:boxdatas
                                    });
                                });
                            });
                        });

                    });
                });
            }
        });
    });
    //提交编辑后的箱子信息
    app.post('/box_management/edit',function(req,res){
        var boxid=req.body.boxid;
        var sim=req.body.sim;
        var buyer=req.body.buyer;
        var code_layout=req.body.code_layout;
        var door_num=req.body.door_num;
        var box_layout=req.body.box_layout;
        var osim=req.body.osim;

        //修改用户名
        if(buyer==0){
            new BoxBuyer().removeBuyerById(boxid,function(err){});
        }else{
            new BoxBuyer().removeBuyerById(boxid,function(err){});
            new Buyer().findBuyerById(buyer,function(datas){
                var buyer_id=datas.buyer_id;
                 var nBoxBuyer=new BoxBuyer({
                        box_id:boxid,
                        buyer_id:buyer_id
                });
                nBoxBuyer.save();
            });
        }
        //修改Sim卡号
        if(sim==0){
            console.log("没有修改Sim卡");
        }else{
            var nboxid="未绑定";
            new Sim().updateIdBySim(osim,nboxid,function(err){});
            new Sim().updateIdBySim(sim,boxid,function(err){});
        }
        //修改箱子信息
        if(code_layout==0){
            if(door_num==0){

            }else{
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateDoorNumById(boxid,doors,door_num,box_layout,function(err){
                });
            }
        }else{
            if(door_num==0){
                new Box().updateCodeById(boxid,code_layout,function(err){});
            }else{
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateAllById(boxid,doors,door_num,box_layout,code_layout,function(err){
                });
            }
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "箱子信息更新成功" //操作内容
        }).save();
        req.flash('success', '箱子信息更新成功.');
        res.redirect('/box_management/box?num=1');
    });

    //箱子详情页面
    app.get('/box_management/box_order',function(req,res){
        var boxid=req.query.boxid;
        new Box().findBoxById(boxid,function(datas){
            var boxDatas=datas;
            new Sim().findSimById(boxid,function(datas){
                var simDatas=datas;
                new BoxBuyer().findBuyerById(boxid,function(datas){
                      if(datas==null){
                          var datas=0;
                          res.render('box_order',{
                              simdatas:simDatas,
                              boxdatas:boxDatas,
                              buyerdatas:datas
                          });
                      }else{
                          var buyer_id=datas.buyer_id;
                          new Buyer().findById(buyer_id,function(datas){
                              var buyerdatas=datas;
                              res.render('box_order',{
                                  simdatas:simDatas,
                                  boxdatas:boxDatas,
                                  buyerdatas:buyerdatas
                              });
                          });
                      }
                });
            });
        });
    });
    //修改Sim卡页面
    app.get('/box_management/update_sim',function(req,res){
        var sim=req.query.sim;
        new Sim().findUserSimById({_id:req.query.id},function(err,doc){
            debug('~~~~~~~~~~~~~~~~');
            console.log(doc);
            debug('~~~~~~~~~~~~~~~~~');
            res.render('update_sim',{id:req.query.id,doc:doc[0]
            });
        });

    });
    app.post('/box_management/update_sim',function(req,res){
        console.log(req.body.page_url+'~~~~~~~~~~~~~~~~~~~~~'+req.body.page_id);
        var options = {
            sim:req.body.sim,
            realsim:req.body.realsim,
            charge:req.body.charge,
            operators:req.body.operators,
            page_title:req.body.page_title,
            page_description:req.body.page_description,
            page_url:req.body.page_url,
            page_comment:req.body.page_comment
        };
        new Sim().updateAllBySim(req.body.id,options,function(err){
            console.log('!!!!!!!!!!!!!!!!!');
            console.log(err);
            console.log('~~~~~~~~~~~~~');
            request.post({url:'http://127.0.0.1/hdc/updatePage', form: {
                page_id:req.body.page_id,
                title:req.body.page_title,
                description:req.body.page_description,
                page_url:req.body.page_url,
                comment:req.body.page_comment

            }}, function(err,httpResponse,body){
                debug('^^^^^^^^^^^^^^^^^^');
                console.log(body);
                debug('~~~~~~~~~~~~~~~~~~~');
            });
            console.log("修改Sim卡信息成功");
        });
        new Sim().findIdBySim(req.body.sim,function(datas){
            if(datas){
               var boxid=datas.box_id;
                new Log({
                    box_id: boxid,
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            }else{
                new Log({
                    box_id: "",
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            }
        });
        req.flash('success', 'Sim卡信息更新成功.');
        return res.redirect('/box_management/code?num=1&&sim=ok');
    });
    //门状态页面
    app.get('/box_management/doors',function(req,res){
        var boxid=req.query.boxid;
        var index=req.query.index;
        if(index==-1){
            var doorsnum=req.query.doorsnum;
            var count = 0;
            async.whilst(function(){
                return count<doorsnum;
            },function(callback) {
                new Box().updateByBoxidAndIndex(boxid, Number(count+1), false, function(data){//false是不为空状态
                    count++;
                    callback();
                });

            },function(err){
                new Box().findByBoxId(boxid, function(box) {
                    var list = box.data;
                    res.render("doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });

                new Log({
                    box_id: boxid,
                    user: req.session.user.user, //操作人
                    date: new Date(), //操作日期
                    operation: "设置为充满物品状态。", //操作内容
                    opertype:"open"
                }).save();
            });

        }else if(index==0) {
            new Box().findByBoxId(boxid, function (box) {
                var list = box.data;
                res.render("doors", {
                    "boxid": boxid,
                    "doordatas": list,
                    "limit": box.boxlimit
                });
            });
        }else if(index=="all"){
            var doorsnum=req.query.doorsnum;
            var doors = [];
            for (var i = 0; i < doorsnum; i++) {
                doors.push({
                    index: i + 1,
                    empty: false,//打开全部后直接设置为不空闲状态，用于填充奖品
                    password: "",
                    opentime: "",
                    owner: "",
                    prize_id:"",
                    discount_price:""
                });
            }
            new Sim().findSimById(boxid,function(datas){
                //client = mqtt.createClient(1883, '114.215.137.61');
                var sim=datas.sim;
                var j=1;
                for (var i = 0; i < doorsnum; i++) {
                    mqttclient.publish(sim, 'open' + j);
                    j++;
                }
            });
            new Box().updateDoorById(boxid,doors,function(){
                new Box().findByBoxId(boxid, function(box) {
                    var list = box.data;
                    res.render("doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });
            });
                new Log({
                    box_id: boxid,
                    user: req.session.user.user, //操作人
                    date: new Date(), //操作日期
                    operation: "打开箱子门:所有", //操作内容
                    opertype:"open"
                }).save();
        }else{
            new Box().updateByBoxidAndIndex(boxid, index, true, function(data){
                Box().findByBoxId(boxid, function(box) {
                    var list = box.data;
                    res.render("doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });
                new Sim().findSimById(boxid,function(datas) {
                    var sim = datas.sim;
                    //client = mqtt.createClient(1883, '114.215.137.61');
                    mqttclient.publish(sim, 'open'+index);
                    //client.end;
                });
                new Log({
                    box_id: boxid,
                    user: req.session.user.user, //操作人
                    date: new Date(), //操作日期
                    operation: "打开箱子门:"+index+"号", //操作内容
                    opertype:"open"
                }).save();
            });
        }
    });

    //用户管理页面
    app.get('/box_management/buyer',function(req,res){
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Buyer().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            res.render('buyerM', {
                datas: datas,
                page: page
            });
        })
    });
    //更新用户资料页面
    app.get('/box_management/update_buyer',function(req,res){
        var id=req.query.id;
        var buyer=req.query.buyer;
        var phoneNum=req.query.phoneNumber;
        var company=req.query.company;
        var level=req.query.level;
        res.render('update_buyer',{
            id:id,
            buyer:buyer,
            phoneNumber:phoneNum,
            company:company,
            level:level
        });
    });
    //提交更新buyer的资料
    app.post('/box_management/update_buyer',function(req,res){
        var id=req.body.id;
        var phoneNumber=req.body.phoneNumber;
        var buyer=req.body.buyer;
        var company=req.body.company;
        var level=req.body.level;
        //修改buyer的资料
        new Buyer().updateBuyerById(id, buyer, phoneNumber, company, level,function (err) {
            new Buyer().findBuyerBy_Id(id,function(datas){
                var buyer_id=datas.buyer_id;
                new BoxBuyer().findIdByBuyer(buyer_id,function(datas){
                    if(datas){
                        for(var i=0;i<datas.length;i++){
                            new Log({
                                box_id: datas[i].box_id,
                                user: "管理员", //操作人
                                date: new Date(), //操作日期
                                operation: "更新用户资料" //操作内容
                            }).save();
                        }
                    }else{
                        new Log({
                            box_id: "",
                            user: "管理员", //操作人
                            date: new Date(), //操作日期
                            operation: "更新用户资料" //操作内容
                        }).save();
                    }
                });
            });
            req.flash('success', '用户资料更新成功.');
            return res.redirect('/box_management/buyer?num=1');
        });
    });
    //新建用户
    app.get('/box_management/create_buyer',function(req,res){
        res.render('create_buyer',{

        });
    });
    //提交新用户资料
    app.post('/box_management/create_buyer',function(req,res){
        var buyer=req.body.buyer;
        var phoneNumber=req.body.phoneNumber;
        var username=req.body.username;
        var password=req.body.password;
        var company=req.body.company;
        var tim=new Date().getTime();
        var nBuyer = new Buyer({
            buyer_id:tim,
            buyer: buyer,
            account:username,
            password:password,
            phoneNumber: phoneNumber, //购买人联系电话
            company: company //购买人所属公司
        });
        new Buyer().findBuyerByBuyer(buyer, function(err, doc) {
            if (doc) err = '用户名已存在,请重新输入.';
            if (err) {
                req.flash('error', err);
                return res.redirect('/box_management/create_buyer?');
            }
            new Buyer().findAccountByAccount(username,function(err,doc){
                if (doc) err = '登陆账号已存在,请重新输入.';
                if (err) {
                    req.flash('error', err);
                    return res.redirect('/box_management/create_buyer?');
                }
                nBuyer.save(function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("OK!");
                    }
                    new Log({
                        box_id:"",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "新建用户(用户名为:"+buyer+")" //操作内容
                    }).save();
                    req.flash('success', '新用户已经生成.');
                    return res.redirect('/box_management/create_buyer');
                });
            });
        });
    });
    //删除Sim卡
    app.get('/box_management/remo_sim',function(req,res){
        var sim=req.query.sim;
        new Sim().findIdBySim(sim,function(datas){
            if(datas.box_id=="未绑定"){
                new Sim().removeSimBySim(sim,function(err){
                    new Log({
                        box_id:"",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "删除Sim卡(号码名为:"+sim+")" //操作内容
                    }).save();
                    req.flash('success', '删除Sim卡成功.');
                    return res.redirect('/box_management/code?num=1&&sim=ok');
                });
            }else{
                req.flash('error', '此Sim卡已绑定箱子，不可删除.');
                return res.redirect('/box_management/code?num=1&&sim=ok');
            }
        });
    });
    //删除用户
    app.get('/box_management/remo_buyer',function(req,res){
        var buyerid=req.query.buyerid;
        var buyer=req.query.buyer;
        new BoxBuyer().findIdByBuyer(buyerid,function(datas){
            if(datas==0){
                new Buyer().removeById(buyerid,function(err){
                });
                new Log({
                    box_id:"",
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "删除用户(用户名为:"+buyer+")" //操作内容
                }).save();
                req.flash('success', '删除用户成功.');
                return res.redirect('/box_management/buyer?num=1');
            }else{
                req.flash('error', '此用户已绑定箱子，不可删除.');
                return res.redirect('/box_management/buyer?num=1');
            }
        });
    });

    //MQTT

    //故障管理
    app.get('/box_management/fault',function(req,res){
        var sess=req.session.user;
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new Log().findOTForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            var dates=[];
            for(var i=0;i<datas.length;i++){
                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
            }
            res.render('faultM', {
                datas: datas,
                dates:dates,
                page: page
            });
        })
    });
    app.get('/user_system/user_fault',function(req,res){
        var account=req.query.account;
        new Buyer().findAccountByAccount(account,function(err,doc){
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    new Sim().findUserSimById(options,function(err,datas){
                        var sims=[];
                        for(var i=0;i<datas.length;i++){
                            sims.push(datas[i].sim);
                        }
                        var page = new Page(req.query.num);
                        var obj = {
                            page: page,
                            search: {sim:{$in:sims}}
                        };
                        new Fault().findForPage(obj,function(err, count, pageCount, datas) {
                            if (err) {
                            }
                            var dates=[];
                            for(var i=0;i<datas.length;i++){
                                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
                            }
                            page.pageCount = pageCount;
                            res.render('user_fault', {
                                datas: datas,
                                dates:dates,
                                page: page,
                                account:account
                            });
                        })
                    });

                }else{
                    req.flash('error', '您没有绑定Sim卡.');
                    return res.redirect('/user_system/main');
                }
            });
        });
    });
    app.get('/user_system/user_update_pwd',function(req,res){
        var account=req.query.account;
        res.render('user_update_pwd',{
            account:account
        });
    });
    app.post('/user_system/user_update_pwd',function(req,res){
        var account=req.body.account;
        var opwd=req.body.opwd;
        var password=req.body.npwd1;
        new Buyer().findPwdByAcc(account,function(err,datas){
            if(err){
                return res.render('update_pwd',{
                    error:'服务器繁忙，请稍后再试！'
                });
            }
            if(datas) {
                if (opwd != datas.password) {
                    return res.render('update_pwd', {
                        error: '旧密码不正确，请重新输入！'
                    });
                }
                new Buyer().updatePwd(account,password,function(err){
                    new Buyer().findPwdByAcc(account,function(err,datas){
                        req.session.user=datas;
                        req.flash('success', '密码修改成功.');
                        return res.redirect('/user_system/user_update_pwd');
                    });

                });
            }
        });
    });

    app.get('/box_management/active',function(req,res){

        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {box_id:req.query.boxid}
        };
        new Active().findForPage(obj, function(err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            res.render('box_active', {
                datas: datas,
                page: page,
                boxid:req.query.boxid
            });
        })

        /*res.render('box_active',{title:'活动管理'});*/
    });
    app.get('/box_management/addActive',function(req,res){
        res.render('add_active',{boxid:req.query.boxid});
    });
    app.post('/box_management/addActive',function(req,res){
        var pathimg= 'public/images/box_active_img/'+req.body.boxid+'/';
        if(!fs.existsSync(pathimg)){
            fs.mkdirSync(pathimg);
        }
        fs.renameSync(req.files.inputfile.path,pathimg+req.files.inputfile.name);
        var active = new Active();
        active.box_id = req.body.boxid;
        active.imgurl = '/images/box_active_img/'+req.body.boxid+'/'+req.files.inputfile.name;
        active.activename = req.body.activename;
        active.content = req.body.content;
        active.status = 0;
        active.date = new Date();
        active.saveActive(function(err){
            return res.redirect('/box_management/active?num=1&boxid='+req.body.boxid);
        });
        //res.render('add_active');
    });

    app.get('/box_management/remActive',function(req,res){
        new Active().removeActiveById(req.query.id,function(err){
            return res.redirect('/box_management/active?num=1&boxid='+req.body.boxid);
        });
    });

    app.get('/box_management/boxM_alarms',function(req,res){
        res.render('boxM_alarms', {
            boxid:req.query.boxid
        });
    });


    /*中奖率设置*/
    app.post('/box_management/setHappyTime',function(req,res){
        var newTimeArr = req.body.newTimeArr;
        var box_id = req.body.boxid;
        var probability = req.body.probability;
        var probability1 = req.body.probability1;
        console.log('~~~~~~~~~~~');
        var alarms=null;
        if(newTimeArr){
            alarms={happy_times:newTimeArr,probability:Number(probability),probability1:Number(probability1)};
        }else{
            alarms={probability1:Number(probability1)};
        }
        new Box().updateColumn({box_id:box_id},alarms,function(err){
            var isadmin = false;
            if(req.session.user.user=='admin'){
                isadmin = true;
            }


            if(err){
               res.send({msg: false, isadmin: isadmin, account: req.session.user.account});
           }else{
               new Sim().findSimById(box_id,function(data){
                   if(newTimeArr){
                       mqttclient.publish('tv'+data.sim,JSON.stringify({type:"HappyTimes",message:newTimeArr+';'+box_id}));
                   }
                   res.send({msg: true, isadmin: isadmin, account: req.session.user.account});
               });


           }
        });
    });

    //设置箱子中奖后是否更新开箱状态
    app.get('/box_management/boxlimit',function(req,res){
        var flag = req.query.limit=='true'?true:false;

        new Box().updateColumn({box_id:req.query.box_id},{limit:flag},function(err) {
            res.redirect('/box_management/doors?boxid='+req.query.box_id+'&&index=0')
        });
    });

};